  // @ts-nocheck
import { ref, reactive } from 'vue';
import { useRoute } from 'vue-router';
import _ from 'lodash';
import OpenSeadragon, { type ViewerEvent } from 'openseadragon';
import { fabric } from 'fabric';
import * as Store from '@/store';
import { ElMessage } from "element-plus";
import { dataInfo, FabricToolOptions } from "../hooks/useInitData";
import useContainerUtils from '@/views/filmRead/hooks/useUtils';
import { updateAnnoData as updateData } from '@/api/readPathology/readPathology';
import type * as FilmReadStoreType from "@/store/modules/filmRead/type";
// 倍率条属性值
const multiplying = ref(40);
const useUtils = (initData: Function) => {
  // const ToolBar = Store.useToolBar();
  // const FilmReadHeader = Store.useFilmReadHeader();
  // const FilmReadLeft = Store.useFilmReadLeft();
  const route = useRoute();
  const FilmRead = Store.useFilmRead();
  const PicStore = Store.usePicContent();
  const ContainerUtilHooks = useContainerUtils();

  // 倍率条更改
  const handleMagnification = (num: number) => {
    dataInfo.viewer && dataInfo.viewer.viewport.zoomTo(num * getActualNum());
  };

  // 初始化设置倍率
  const initZoom = () => {
    dataInfo.viewer.addHandler('zoom', (options: ViewerEvent) => {
      options.zoom && (multiplying.value = Math.round((options.zoom / getActualNum()) * 10) / 10);

      /*console.log('dragon-zoom', options)
      if(options.refPoint == null) return
      console.log(options.zoom,dataInfo.viewer.viewport.getZoom(),getActualNum(),dataInfo.viewer.viewport.getZoom(true),dataInfo.slideInfo.Width,dataInfo.viewer.viewport._containerInnerSize.x)
      // this.viewer.viewport.getZoom(true) / this.fabricjsOverlay.getActualValue(); //当前倍率
      const zoom = dataInfo.viewer.viewport.getZoom(true) / getActualNum()
      ///options.zoom / getActualNum()//(dataInfo.viewer.viewport._containerInnerSize.x * dataInfo.viewer.viewport.getZoom(true))
      const point = new OpenSeadragon.Point(options.refPoint.x, options.refPoint.y);
      const zoomPoint = dataInfo.viewer?.viewport.imageToViewportZoom(point)
      dataInfo.frabicCanvas.zoomToPoint(zoomPoint,zoom)*/
    });
  };

  // 获取实际比例
  const getActualNum = () => {
    const originImgWidth = Number(dataInfo.slideInfo.Width);
    const Magnification = Number(dataInfo.slideInfo.Magnification) || 20;
    const containerWidth = Number(dataInfo.viewer.container.clientWidth);
    return originImgWidth / Magnification / containerWidth;
  };

  // 工具栏操作
  const handleToolBar = (item: Header.ToolBarItem) => {
    //绘画工具反选
    if (!item.currentItem.isActive && ["RECTANGLE", "ELLIPSE",'CLOSEDCURVE','rule','move'].includes(item.currentItem.code)) {
      dataInfo.currentToolItem = {};
      setZoomActive();
      return;
    }
    if(!['reset', 'delRule'].includes(item.currentItem.code)){//重置和删除尺子不记录,不然影响重置的逻辑
      dataInfo.currentToolItem = item;
    }
    switch (item.currentItem.name) {
      case '缩放':
        setZoomActive();
        break;
      case '移动':
        dataInfo.viewer && dataInfo.viewer.setMouseNavEnabled(true);
        dataInfo.frabicCanvas.isDrawingMode = false
        dataInfo.isDefault = false;
        dataInfo.doDrawing = false;
        _handleToolBar(1.1, true, true);
        break;
      case '重置':
        dataInfo.viewer && dataInfo.viewer.viewport.goHome(false);
        /*nextTick(() => {
          setZoomActive()
        });*/
        break;
      case '删除尺子':
        // store进行存储
        dataInfo.frabicCanvas.getObjects()
            .filter((item) => item.type === 'line' || item.type === 'text')
            .map((item) => dataInfo.frabicCanvas.remove(item));
        // 删除尺子
        PicStore.clearState();
        dataInfo.isDefault = false;
        break;
      case '尺子':
      case '矩形':
      case '椭圆':
        // dataInfo.viewer && dataInfo.viewer.setMouseNavEnabled(false);
        dataInfo.frabicCanvas.isDrawingMode = false
        // 绘制图形
        dataInfo.isDefault = false;
        dataInfo.doDrawing = true;
        break;
      case '闭合曲线':
        dataInfo.isDefault = false;
        dataInfo.doDrawing = true;
        dataInfo.frabicCanvas.isDrawingMode = item.isTool
        break
      default:
        dataInfo.doDrawing = false;
        _handleToolBar(1.1, false, false);
        break;
    }
  };

  const setZoomActive = () => {
    dataInfo.viewer && dataInfo.viewer.setMouseNavEnabled(true);
    dataInfo.frabicCanvas.isDrawingMode = false
    dataInfo.isDefault = false;
    dataInfo.doDrawing = false;
    _handleToolBar(1.1, false, false);
  }
  // 限制操作辅助函数
  const _handleToolBar = (
    num: number,
    levelFlag: boolean,
    verticalFlag: boolean
  ) => {
    dataInfo.viewer.zoomPerScroll = num;
    dataInfo.viewer.panHorizontal = levelFlag;
    dataInfo.viewer.panVertical = verticalFlag;
  };

  // 病灶列表操作
  const handleLesionClick = async (item: any) => {
    const allObjs = dataInfo.frabicCanvas.getObjects();
    // 全部显示删除
    if (item.type === 'all') {
      allObjs.map(obj => {
        obj.set('visible', item.isShowAll);
        (route.query.type !== 'query') && obj.set('hasControls', item.isShowAll);
        (route.query.type === 'query') && obj.set('hasBorders', item.isShowAll);
      })
      dataInfo.frabicCanvas.renderAll();
    }
    // 单一病灶显示隐藏
    if (item.type === 'eyes') {
      const selectedObjs = allObjs.filter(it => it.id === item.id)//包含path-control
      selectedObjs.map(obj => {
        obj.set('visible', item.isEyes);
        (route.query.type !== 'query') && obj.set('hasControls', item.isEyes);
        (route.query.type === 'query') && obj.set('hasBorders', item.isEyes);
      })
      dataInfo.frabicCanvas.renderAll();
    }
    // 修改颜色
    if (item.type === 'color') {
      if (FilmRead.dictionaryData.imageDataList) {
        const params = {
          alrId: item.currentItem.id,
          result: JSON.stringify(FilmRead.dictionaryData.imageDataList[item.currentItem.id].result),
          color: item.value,
        };
        const res = await updateData(params);
        ElMessage.success('修改成功！');
        // 调整数据
        // 改病灶颜色
        // 由于是v-model的数据，所以不需要变更原始数据的color
        const selectedObj = allObjs.find(it => it.id === item.currentItem.id)
        selectedObj && selectedObj.set('stroke', item.value);
        dataInfo.frabicCanvas.renderAll();
      }
    }
    // 删除病灶
    if (item.type === 'del') {
      const currentObj = allObjs.find((it) => it.id === item.id)
      currentObj && dataInfo.frabicCanvas.remove(currentObj);
      currentObj && removePathControl(currentObj.id)
      dataInfo.frabicCanvas.renderAll();
      ContainerUtilHooks.lesionEvent.lesionDel(item.id);
    }
    // 点击切换病灶
    if (item.type === 'lesion') {
      // 刷新左侧的病灶列表
      const currentObj = allObjs.find(it => item.id === it.id);
      if (currentObj) {
        if(item.isLesion === '') { // 反选
          dataInfo.frabicCanvas.discardActiveObject().renderAll();
          currentObj.type === 'CLOSEDCURVE' && removePathControl(currentObj.id)
        } else {
          dataInfo.frabicCanvas.setActiveObject(currentObj).renderAll();
          const { width, height, left, top } = currentObj
          const point = new OpenSeadragon.Point(left + width/2, top + height/2);
          const viewportPoint = dataInfo.viewer.viewport.viewerElementToViewportCoordinates(point)
          // const viewportPoint = dataInfo.viewer.viewport.deltaPointsFromPixels(p);
          // const zoom = currentObj.acZoom * getActualNum();
          // dataInfo.viewer.viewport.zoomTo(zoom); // 缩放到画时的倍率,path类型可能会乱，产品不需要
          dataInfo.viewer.viewport.panTo(viewportPoint);
          /*setTimeout(() => {//不然会定位不准
            dataInfo.viewer.viewport.panTo(viewportPoint); // 不然会定位不准
          }, 200);*/
        }
      }
    }
  }

  // 根据数据梳理左侧病灶标注对象 并表示初始渲染调用此方法
  // LesionType.NidusList extends ToolBarType.ShowComponentObj
  const getMarkObj = (item: FilmReadStoreType.LesionItem) => {
    let markObj: any;
    if (typeof item.result === "string") item.result = JSON.parse(item.result || "{}");
    const { data, acZoom, version } = item.result as unknown as {[x: string | number]: any};

    const nzoom = dataInfo.viewer.viewport.getZoom() / getActualNum();
    let currentLesionObj: FilmReadStoreType.LesionItem = FilmRead.dictionaryData.lesionDataList && FilmRead.dictionaryData.lesionDataList[item.id];
    // FilmRead.dictionaryData.lesionDataList && (currentLesionObj = FilmRead.dictionaryData.lesionDataList[item.id]);
    if (currentLesionObj.tool === 'RECTANGLE') {
      const newData = {
        point1: { ...changePoint(data.point1) },
        point2: { ...changePoint(data.point2) },
      };
      markObj = new fabric.Rect({
        ...FabricToolOptions,
        top: Math.min(newData.point1.y, newData.point2.y),
        left: Math.min(newData.point1.x, newData.point2.x),
        width: Math.abs(newData.point1.x - newData.point2.x),
        height: Math.abs(newData.point1.y - newData.point2.y),
        // cornerColor: '#1FFF79',
        // borderColor: '#1FFF79',
        // cornerSize: 10,
        type: 'rect',
        stroke: currentLesionObj.color,
        // strokeWidth: 1,
        fill: "rgba(255, 255, 255, 0)",
        // hasControls: true,
        // hasBorders: false,
        // transparentCorners: false,
        // perPixelTargetFind: true,
        // lockRotation: true,
        // selectable: true,
        // centeredScaling: false,
        // strokeUniform: true,
        originX: 'left',
        originY: 'top',
        // visible: true,
        // statefullCache: true,
        // borderScaleFactor: 10
      });
      // dataInfo.frabicCanvas.skipTargetFind = false;
      // dataInfo.frabicCanvas.selection = true;
      // dataInfo.frabicCanvas.selectionColor = 'transparent';
      // dataInfo.frabicCanvas.selectionBorderColor = currentLesionObj.color;
    }else if (currentLesionObj.tool === 'ELLIPSE') {
      const newData = {
        point1: { ...changePoint(data.point1) },
        point2: { ...changePoint(data.point2) },
      };
      let rx = Math.abs(newData.point1.x - newData.point2.x) / 2;
      let ry = Math.abs(newData.point1.y - newData.point2.y) / 2;
      let top =
      newData.point2.y > newData.point1.y ? newData.point1.y : newData.point1.y - ry * 2;
      let left =
      newData.point2.x > newData.point1.x ? newData.point1.x :  newData.point1.x - rx * 2;
      // rx = (rx / acZoom) * nzoom;
      // ry = (ry / acZoom) * nzoom;
      // top = (top / acZoom) * nzoom;
      // left = (left / acZoom) * nzoom;
      markObj = new fabric.Ellipse({
        ...FabricToolOptions,
        top,
        left,
        rx,
        ry,
        // cornerColor: '#1FFF79',
        // borderColor: '#1FFF79',
        // cornerSize: 10,
        type: 'ellipse',
        stroke: currentLesionObj.color,
        // strokeWidth: 1,
        // fill: "rgba(255, 255, 255, 0)",
        // hasControls: true,
        // hasBorders: false,
        // transparentCorners: false,
        // perPixelTargetFind: true,
        // lockRotation: true,
        // centeredScaling: false,
        // strokeUniform: true,
        originX: 'left',
        originY: 'top',
        // visible: true,
        // statefullCache: true,
        // borderScaleFactor: 10
      });
      // dataInfo.frabicCanvas.skipTargetFind = false;
      // dataInfo.frabicCanvas.selection = true;
      // dataInfo.frabicCanvas.selectionColor = 'transparent';
      dataInfo.frabicCanvas.selectionBorderColor = currentLesionObj.color;
    }else if(currentLesionObj.tool === 'CLOSEDCURVE'){
      const pathArr = pathPointConvert(data.path, imageToFabric)
      const { color: stroke, tool: type } = currentLesionObj
      const id = item.id
      const strokeWidth = 1
      const fill = 'transparent'
      markObj = new fabric.Path(pathArr.flat().join(" "),{...FabricToolOptions,id, type, stroke, strokeWidth, fill, acZoom})
    }
    markObj.set('id', item.id);
    markObj.set('acZoom', acZoom);
    dataInfo.frabicCanvas.add(markObj)//.renderAll();
    // dataInfo.frabicCanvas?.add(markObj!).requestRenderAll();
    return markObj;
  };

  // 坐标转换工具函数:false - 大图转window，true - window转大图
  const changePoint = (
    point: { x: number; y: number },
    type: boolean = false
  ): { x: number; y: number } => {
    let result = {
      x: 0,
      y: 0,
    };
    const offset =
      dataInfo.frabicCanvas.calcOffset().viewportTransform || [];
    // 记录画布鼠标按下时的x偏移量
    const offsetX = offset[4];
    // 记录画布鼠标按下时的y偏移量
    const offsetY = offset[5];
    const boundsNoRotate = dataInfo.viewer.viewport.getBoundsNoRotate(true);
    const boundsNoRotatePoint = new OpenSeadragon.Point(
      boundsNoRotate.x,
      boundsNoRotate.y
    );
    const boundsNoRotateWindowPoint =
      dataInfo.viewer.viewport.viewportToWindowCoordinates(
        boundsNoRotatePoint
      );
    if (type) {
      point.x = point.x + offsetX + boundsNoRotateWindowPoint.x;
      point.y = point.y + offsetY + boundsNoRotateWindowPoint.y;
      point.x = Math.round(point.x);
      point.y = Math.round(point.y);
      const newPoint = new OpenSeadragon.Point(point.x, point.y);
      const imgPoint =
        dataInfo.viewer.viewport.windowToImageCoordinates(newPoint);
      result = imgPoint;
    } else {
      const openPoint = new OpenSeadragon.Point(point.x, point.y);
      const windowPoint = dataInfo.viewer.viewport.imageToWindowCoordinates(openPoint);
      windowPoint.x = windowPoint.x - boundsNoRotateWindowPoint.x - offsetX;
      windowPoint.y = windowPoint.y - boundsNoRotateWindowPoint.y - offsetY;
      // windowPoint.x = Math.round(windowPoint.x);
      // windowPoint.y = Math.round(windowPoint.y);
      result = windowPoint;
    }
    return result;
  };
  //path点位坐标数组转换
  const pathPointConvert = (pathPoints: [], converter: Function) => {
    return pathPoints.map((p: any) => {
      let tt = []
      if(p && p[0]){
        tt[0] = p[0]
      }
      if(p && p[1] && p[2]){
        const p1 = converter({x: p[1], y: p[2]})
        tt[1] = p1.x
        tt[2] = p1.y
      }
      if(p && p[3] && p[4]){
        const p2 = converter({x: p[3], y: p[4]})
        tt[3] = p2.x
        tt[4] = p2.y
      }
      return tt
    })
  }
  //大图坐标转fabric
  const imageToFabric = (point: {x: number; y: number}) => {
    const offsetX = dataInfo.frabicCanvas?.viewportTransform[4]
    const offsetY = dataInfo.frabicCanvas?.viewportTransform[5]
    const pos = new OpenSeadragon.Point(point.x, point.y)
    const p = {...dataInfo.viewer?.viewport.imageToViewerElementCoordinates(pos)}
    return { x: p.x - offsetX, y: p.y - offsetY }
  }
  //fabric坐标转大图
  const fabricToImage = (point: {x: number; y: number}) => {
    const offsetX = dataInfo.frabicCanvas?.viewportTransform[4]
    const offsetY = dataInfo.frabicCanvas?.viewportTransform[5]
    const px = point.x + offsetX
    const py = point.y + offsetY
    const pos = new OpenSeadragon.Point(px, py);
    return {...dataInfo.viewer.viewport.viewerElementToImageCoordinates(pos)}
  }
  // 尺子回显
  const getLocalRuler = () => {
    const note = PicStore.markData;
    if (dataInfo.viewer) {
      // 获取实际倍率
      const nzoom = dataInfo.viewer.viewport.getZoom() / getActualNum();
      note.objects.map(
        (item: {
          id: number,
          data: {
            point1: { x: number; y: number };
            point2: { x: number; y: number };
          };
          acZoom: number;
          acWidth: number;
          acHeight: number;
        }) => {
          const { data, id, lineLength } = item;
          const newData = {
            point1: { ...changePoint(data.point1) },
            point2: { ...changePoint(data.point2) },
          };
          const canvasObject = new fabric.Line(
            [
              newData.point1.x,
              newData.point1.y,
              newData.point2.x,
              newData.point2.y,
            ],
            {
              ...FabricToolOptions,
              type: 'line',
              originX: 'center',
              originY: 'center',
              stroke: dataInfo.ruleInfo.color,
              id
            }
          );

          const textObject = new fabric.Text(`${lineLength}mm`, {
            top: newData.point2.y,
            left: newData.point2.x,
            fontSize: 16,
            stroke: dataInfo.ruleInfo.color,
            // originX: 'center',
            // originY: 'center',
            id
          });
          /*const group = new fabric.Group([canvasObject, textObject], {
            type: 'group',
            // borderColor: 'transparent', // 边框颜色
            // cornerColor: 'transparent', // 控制角颜色
            // cornerSize: 10, // 控制角大小
            // 控制器是否为填充 true为透明 false为填充
            transparentCorners: false,
            hasControls: false,
            lockScalingX: true,
            lockScalingY: true,
            lockRotation: true,
            lockMovementX: true,
            lockMovementY: true,
            perPixelTargetFind: true,
            // originX: 'center',
            // originY: 'top',
            ...item
          });*/
          // dataInfo.frabicCanvas.add(group);
          // dataInfo.frabicCanvas.add(group).renderAll();
          dataInfo.frabicCanvas.add(canvasObject, textObject).renderAll();
        }
      );
    }
  };
  //重绘overlay
  const updateAnnoData = (e) => {
    // 获取当前渲染的所有canvas图像
    let canvasObjs = dataInfo.frabicCanvas.getObjects();
    const activeObjects = dataInfo.frabicCanvas.getActiveObjects()
    dataInfo.frabicCanvas.remove(...canvasObjs/*.filter(it => it.type !== 'path-control')*/);
    // 获取当前所有的数据字典
    const resultList = FilmRead.dictionaryData.imageDataList;
    canvasObjs = canvasObjs.filter(it => it.type !== 'path-control').map(item => {
      if (resultList && ['rect','ellipse'].includes(item.type)) {
        const currentItem = resultList[item.id];
        if(currentItem == undefined) return item
        const { id, result } = currentItem;
        // if (typeof result === "string") result = JSON.parse(result || "{}");
        const { acZoom, data, version } = result;
        const newData = {
          point1: { ...changePoint(data.point1) },
          point2: { ...changePoint(data.point2) },
        }
        if (item.type === 'rect') {
          item.set("top", Math.min(newData.point1.y, newData.point2.y));
          item.set("left", Math.min(newData.point1.x, newData.point2.x));
          item.set("width", Math.abs(newData.point1.x - newData.point2.x));
          item.set("height", Math.abs(newData.point1.y - newData.point2.y));
        }
        if (item.type === 'ellipse') {
          let rx = Math.abs(newData.point1.x - newData.point2.x) / 2;
          let ry = Math.abs(newData.point1.y - newData.point2.y) / 2;
          let top =
          newData.point2.y > newData.point1.y ? newData.point1.y : newData.point1.y - ry * 2;
          let left =
          newData.point2.x > newData.point1.x ? newData.point1.x :  newData.point1.x - rx * 2;
          item.set("top", top);
          item.set("left", left);
          item.set("rx", rx);
          item.set("ry", ry);
        }
      }else if (item.type === 'group') {
        const objectDatas = PicStore.markData.objects;
        const currentData = objectDatas.find(it => it.id === item.id);
        if (currentData) {
          const newData = {
            point1: { ...changePoint(currentData.data.point1) },
            point2: { ...changePoint(currentData.data.point2) },
          }
          item.item(0).set("x1", newData.point1.x)
          item.item(0).set("y1", newData.point1.y)
          item.item(0).set("x2", newData.point2.x)
          item.item(0).set("y2", newData.point2.y)
          item.item(1).set("top", newData.point2.y)
          item.item(1).set("left", newData.point2.x)
          // item._updateObjectCoords(,)
          // item._updateObjectsACoords()
          item._updateObjectsCoords()
        }
      }else if(item.type === 'line'){
        const objectDatas = PicStore.markData.objects;
        const currentData = objectDatas.find(it => it.id === item.id);
        if (currentData) {
          const newData = {
            point1: {...changePoint(currentData.data.point1)},
            point2: {...changePoint(currentData.data.point2)},
          }
          item.set("x1", newData.point1.x)
          item.set("y1", newData.point1.y)
          item.set("x2", newData.point2.x)
          item.set("y2", newData.point2.y)
        }
      }else if(item.type === 'text'){
        const objectDatas = PicStore.markData.objects;
        const currentData = objectDatas.find(it => it.id === item.id);
        if (currentData) {
          const newData = {
            point1: {...changePoint(currentData.data.point1)},
            point2: {...changePoint(currentData.data.point2)},
          }
          item.set("left",newData.point2.x)
          item.set("top", newData.point2.y)
          item.set("lineLength", currentData.lineLength)
          item.set("fontSize", 16)
        }
      }else if(item.type === 'CLOSEDCURVE'){
        const currentItem = resultList[item.id];
        if(currentItem == undefined) return false
        const { result } = currentItem;
        const { acZoom, data, version } = result;
        const pathArr = pathPointConvert(data.path, imageToFabric)
        const { id, type, stroke, strokeWidth, fill, visible, hasControls} = item
        item = new fabric.Path(pathArr.flat().join(" "),{...FabricToolOptions, id, type, stroke, strokeWidth, fill, visible,hasControls, acZoom})
      }else if(item.type === 'path-control'){
        //todo 重绘曲线控制点
        const currentItem = resultList[item.id];
        if(currentItem == undefined) return false
        const { result } = currentItem;
        const { acZoom, data, version } = result;
        const pArr = data.path[item.idx]
        let p = {}
        if(pArr[0] === 'M' || pArr[0] === 'L'){
          p.x = pArr[1]
          p.y = pArr[2]
        }else if(pArr[0] === 'Q'){
          p.x = pArr[3]
          p.y = pArr[4]
        }
        if(!p.x || !p.y) return false
        const pp = imageToFabric(p)
        item.set('left', pp.x - item.radius)
        item.set('top', pp.y - item.radius)
      }else{
        //todo
      }
      if (route.query.type === 'query') {
        item.set({
          lockMovementX: true,
          lockMovementY: true,
          lockRotation: true,
          lockScalingFlip: true,
          lockScalingX: true,
          lockScalingY: true,
          lockUniScaling: true,
          hasControls: false,
          hasBorders: true,
          borderColor: '#1FFF79',
          borderScaleFactor: 2,
          selectable: false,
        })//只读模式
      }
      return item
    })
    dataInfo.frabicCanvas.add(...canvasObjs.filter(it => it.type !== 'path-control'))
    activeObjects.map(it => {
      const activeItem = canvasObjs.find(item => item.id === it.id)
      activeItem && dataInfo.frabicCanvas.setActiveObject(activeItem)
      if(activeItem && activeItem.type  === 'CLOSEDCURVE' && route.query.type !== 'query'){
        addPathControl(it.id)
      }
    })
    dataInfo.frabicCanvas.renderAll();//.requestRenderAll()
  }
  //删除曲线的控制点
  const removePathControl = (id) => {
    const oldControlArr = getOverlaysByIdAndType(id, 'path-control')
    //删除old
    oldControlArr && dataInfo.frabicCanvas.remove(...oldControlArr);
  }
  //生成并显示曲线控制点
  const addPathControl = /*_.debounce(*/(id) => {
    const currPathArr = getOverlaysByIdAndType(id, 'CLOSEDCURVE')
    //todo 避免重复添加?
    if(currPathArr.length > 0 && currPathArr[0].path){
      //让path无法修改
      currPathArr[0].set('hasControls', false)
      currPathArr[0].set('selectable', false)
      currPathArr[0].set('selection', false)
      currPathArr[0].set('skipTargetFind', false)
      // currPathArr[0].set('perPixelTargetFind', false)
      const currControlArr = currPathArr[0].path.filter(pp => pp[1] && pp[2]).map((p, index) => {
        if(p[0] === 'M' || p[0] === 'L'){
          return createPathPoint(+id, 'path-control', index, p[1] ,p[2])
        }else if(p[0] === 'Q'){
          return createPathPoint(+id, 'path-control', index, p[3] ,p[4])
        }
      })
      //添加curr
      currControlArr && dataInfo.frabicCanvas.add(...currControlArr);
      // currControlArr && currControlArr.map((c)=>{dataInfo.frabicCanvas.setActiveObject(c)});//todo 使操作点在前面
      return currControlArr
    }
    return []
  }/*, 100,{ leading: false, trailing: true })*/
  //
  const getOverlayById = (id: string) => {
    const allObj = dataInfo.frabicCanvas?.getObjects()
    return allObj.find((it)=> it.id === +id)
  }

  const getOverlaysByIdAndType = (id: string, type: string) => {
    const allObj = dataInfo.frabicCanvas?.getObjects()
    return allObj.filter((it)=> it.id === +id && it.type === type)
  }
  const createPathPoint = (id: number, type: string, idx: number, x: number, y: number) => {
    const radius = 4
    const left = x - radius
    const top = y - radius
    const c = new fabric.Circle({
      ...FabricToolOptions,
      id,
      idx,
      type,
      left,
      top,
      strokeWidth: 1,
      radius,
      fill: '#dc6a06',
      stroke: '#fff',
      hoverCursor: 'crosshair',
      moveCursor: 'crosshair',
      skipTargetFind: false,
      perPixelTargetFind: false,
      hasBorders: false,
      hasControls: false,
    });

    return c;
  }
  //把fabric画布原点与大图的左上角重合？
  const resetFabricCanvas = () => {
    const origin = new OpenSeadragon.Point(0, 0);
    const viewportWindowPoint = dataInfo.viewer.viewport.viewportToWindowCoordinates(origin);
    const x = viewportWindowPoint.x;
    const y = viewportWindowPoint.y;
    const canvasOffset = dataInfo.fabricToolCanvas.getBoundingClientRect();
    const pageScroll = OpenSeadragon.getPageScroll();
    dataInfo.frabicCanvas?.absolutePan(
        new fabric.Point(canvasOffset.left - x + pageScroll.x, canvasOffset.top - y + pageScroll.y)
    );
  }

  return reactive({
    multiplying,
    initZoom,
    handleMagnification,
    handleToolBar,
    handleLesionClick,
    getActualNum,
    getMarkObj,
    changePoint,
    getLocalRuler,
    updateAnnoData,
    setZoomActive,
    imageToFabric,
    fabricToImage,
    pathPointConvert,
    getOverlayById,
    getOverlaysByIdAndType,
    createPathPoint,
    addPathControl,
    removePathControl,
    resetFabricCanvas
  });
};
export default useUtils;
